﻿using System.Threading;
using ZeroMQ;
using ZHello.MQ;

namespace ZHello.Net.MQ.ZeroMQ
{
    /// <summary>
    ///
    /// </summary>
    internal class ZeroReqClient : IReqClient
    {
        private ZSocket Socket { get; set; }

        public ZeroReqClient(string addr)
        {
            ZSocket socket;
            if (ZeroHelper.CreateReqClient(addr, out socket))
            {
                Socket = socket;
            }
        }

        public void Dispose()
        {
            Socket.Dispose();
        }

        public bool SendAndRecv(string send, out string recv, out string error)
        {
            if (send == null)
            {
                error = "不能发送NULL";
                recv = null;
                return false;
            }
            var b = false;
            error = null;
            recv = null;
            ZError zError;
            if (Socket.SendOnce(send, out zError))
            {
                do
                {
                    recv = Socket.RecvOnce(out zError);
                    Thread.Sleep(5);
                } while (recv == null);
                if (zError == null)
                {
                    b = true;
                }
            }
            if (zError != null)
            {
                error = zError.Text;
            }
            return b;
        }
    }
}